
package com.yuan.unit;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 地图工具类 用在搜索地址
 * 
 * @author YUAN
 */
public class MapHelper {
    public final static String TAG = "MapHelper";
    private static List<GeocodeAddress> listadress;
    private static GeocodeQuery geocodequery;
    private GeocodeSearch geocodesearch = null;
    private RegeocodeQuery regeocodequery = null;
    private RegeocodeAddress regeocodeaddress = null;
    private static MapHelper sInstance;

    private MapHelper()
    {
        geocodequery = new GeocodeQuery(null, null);
        listadress = new ArrayList<GeocodeAddress>();
    }

    public static MapHelper getInstance() {
        if (sInstance == null) {
            synchronized (MapHelper.class) {
                if (sInstance == null) {
                    sInstance = new MapHelper();
                }

            }
        }
        return sInstance;
    }

    public synchronized List<GeocodeAddress> SearchGPSFromLocalName(
            Context context, String adress, String city) {
        listadress.clear();
        if (geocodesearch == null) {
            geocodesearch = new GeocodeSearch(context);
        }
        geocodequery.setLocationName(adress);
        geocodequery.setCity(city);
        try {
            listadress = geocodesearch.getFromLocationName(geocodequery);
        } catch (AMapException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return listadress;
    }

    public synchronized String SearchLocalNameFromGPS(
            Context context, LatLonPoint point) {
        if (regeocodequery == null) {
            regeocodequery = new RegeocodeQuery(point, 100, GeocodeSearch.AMAP);
        }
        regeocodequery.setPoint(point);
        if (geocodesearch == null)
        {
            geocodesearch = new GeocodeSearch(context);
        }
        try {
            regeocodeaddress = geocodesearch.getFromLocation(regeocodequery);
        } catch (AMapException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return regeocodeaddress.getFormatAddress();
    }

    public void onDestroy() {
        // TODO Auto-generated method stub
        listadress = null;
        geocodequery = null;
        geocodesearch = null;
        sInstance = null;
    }
}
